import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/Login.vue";

Vue.use(VueRouter);

const routes = [
  { path: "/", redirect: "/classify" },
  { path: "/login", component: Login },
  {
    path: "/scanTheCode",
    name: "scanTheCode",
    component: () => import("../views/scanTheCode.vue"),
  },
  {
    path: "/index",
    name: "index",
    component: () => import("../views/index.vue"),
    children: [
      {
        path: "/classify",
        name: "classify",
        component: () => import("../components/container/classify.vue"),
      },
      {
        path: "/manage",
        name: "manage",
        component: () => import("../components/container/manage.vue"),
      },
      {
        path: "/commodityPage",
        name: "commodityPage",
        component: () => import("../components/container/CommodityPage.vue"),
      },
    ],
  },
  {
    path: "*",
    name: "404",
    component: () => import("../views/404.vue"),
  }
];

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes,
});

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path == "/login") return next();
  if (to.path == "/scanTheCode") return next();
  // 获取token
  const tokenStr = localStorage.getItem("kua_token");
  if (!tokenStr) return next("/login");
  next();
});

export default router;
